from datetime import datetime, date
from decimal import Decimal
from server import base_path, app
from os import path, remove
import time

ALLOW_SUFFIX = {"jpg", "jpeg", "png", "gif", "bmp", "pdf", "JPG", "JPEG", "PBG", "GIF", "BMP", "PDF"}


def save_image(image, model, folder, attr=None):
    # 图片存储
    suffix = image.filename.rsplit('.', 1)[1]
    # if suffix not in ALLOW_SUFFIX:
    #     return False, {'code': 50003, 'message': "文件格式错误, 仅支持图片或PDF."}
    image_name = '%s_file_%s.%s' % (folder, round(time.time() * 1000), suffix)
    address = path.join(folder + "/", image_name)
    image.save(path.join(app.config['UPLOAD_PATH'], address))
    if attr:
        setattr(model, attr, address)
    else:
        model.image_url = address
    # model.attr = address
    return True, None


def remove_image(image_url):
    old_img = path.join(base_path, image_url)
    if path.isfile(old_img):
        remove(old_img)


class PERMISSION:
    NONE = 0  # 无权限
    ADD = 0x01  # 增
    DELETE = 0x02  # 删
    EDIT = 0x04  # 改
    QUERY = 0x08  # 查
    CRUD = 0x0f  # 增删查改 需要异或

    @staticmethod
    def crud(per):
        return [PERMISSION.can_add(per), PERMISSION.can_delete(per), PERMISSION.can_edit(per), PERMISSION.can_query(per)]

    @staticmethod
    def li_to_per(li):
        permission = 0
        for i in range(len(li)):
            if li[i] is True:
                permission |= (1 << i)
        return permission

    @staticmethod
    def can_query(per):
        return per & PERMISSION.QUERY == PERMISSION.QUERY

    @staticmethod
    def can_add(per):
        return per & PERMISSION.ADD == PERMISSION.ADD

    @staticmethod
    def can_edit(per):
        return per & PERMISSION.EDIT == PERMISSION.EDIT

    @staticmethod
    def can_delete(per):
        return per & PERMISSION.DELETE == PERMISSION.DELETE


def set_field(obj_db, data):
    for key in obj_db.__table__.columns.keys():
        if key in data:
            value = data[key]
            if value == "0" or value == "1":
                value = int(value)
            setattr(obj_db, key, value)


def query_by_field(query, filter_json, model):
    if not filter_json:
        return query
    import json
    query_filter = json.loads(filter_json)
    for k, v in query_filter.items():
        if not v:
            continue
        query = query.filter(getattr(model, k) == v)
    return query


def str_judge(obj):
    if isinstance(obj, datetime) or isinstance(obj, date) or isinstance(obj, Decimal):
        return str(obj)
    return obj


ALLOW_SUFFIX = {"jpg", "jpeg", "png", "gif", "bmp", "pdf", "JPG", "JPEG", "PBG", "GIF", "BMP", "PDF"}
